// 服务状态检查工具
const FACE_API_CONFIG = {
  COMPARE_URL: 'http://localhost:1001/face/compare',
  THRESHOLD_INFO_URL: 'http://localhost:1001/face/threshold-info'
};

/**
 * 检查后端服务状态
 */
class ServiceChecker {
  
  /**
   * 检查人脸识别服务状态
   */
  static async checkFaceServiceStatus() {
    console.log('=== 检查人脸识别服务状态 ===');
    
    try {
      // 检查阈值信息接口
      const thresholdResponse = await this.checkThresholdInfo();
      if (thresholdResponse.success) {
        console.log('✅ 阈值信息接口正常');
      } else {
        console.log('❌ 阈值信息接口异常:', thresholdResponse.error);
      }
      
      // 检查人脸识别接口（使用测试数据）
      const recognizeResponse = await this.checkRecognizeService();
      if (recognizeResponse.success) {
        console.log('✅ 人脸识别接口正常');
      } else {
        console.log('❌ 人脸识别接口异常:', recognizeResponse.error);
      }
      
      return {
        success: thresholdResponse.success && recognizeResponse.success,
        threshold: thresholdResponse,
        recognize: recognizeResponse
      };
      
    } catch (error) {
      console.error('❌ 服务检查失败:', error);
      return {
        success: false,
        error: error.message
      };
    }
  }
  
  /**
   * 检查阈值信息接口
   */
  static async checkThresholdInfo() {
    return new Promise((resolve) => {
      wx.request({
        url: FACE_API_CONFIG.THRESHOLD_INFO_URL,
        method: 'GET',
        timeout: 10000,
        success: (res) => {
          if (res.statusCode === 200) {
            try {
              const result = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
              if (result.suggested_threshold) {
                resolve({
                  success: true,
                  data: result,
                  message: '阈值信息接口正常'
                });
              } else {
                resolve({
                  success: false,
                  error: '阈值信息格式错误',
                  data: result
                });
              }
            } catch (parseError) {
              resolve({
                success: false,
                error: '解析响应失败: ' + parseError.message,
                data: res.data
              });
            }
          } else {
            resolve({
              success: false,
              error: `HTTP ${res.statusCode}: ${res.data}`,
              statusCode: res.statusCode
            });
          }
        },
        fail: (error) => {
          resolve({
            success: false,
            error: '网络请求失败: ' + error.errMsg
          });
        }
      });
    });
  }
  
  /**
   * 检查人脸识别接口
   */
  static async checkRecognizeService() {
    return new Promise((resolve) => {
      // 使用一个小的测试图片Base64
      const testImageBase64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';
      
      wx.request({
        url: FACE_API_CONFIG.COMPARE_URL,
        method: 'POST',
        data: {
          img1Base64: testImageBase64,
          img2Base64: testImageBase64
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        timeout: 15000,
        success: (res) => {
          if (res.statusCode === 200) {
            try {
              // 检查是否为HTML响应
              if (typeof res.data === 'string' && res.data.includes('<!doctype html>')) {
                resolve({
                  success: false,
                  error: '收到HTML响应，服务可能未启动',
                  data: res.data.substring(0, 200) + '...'
                });
                return;
              }
              
              const result = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
              resolve({
                success: true,
                data: result,
                message: '人脸识别接口正常'
              });
            } catch (parseError) {
              resolve({
                success: false,
                error: '解析响应失败: ' + parseError.message,
                data: res.data
              });
            }
          } else {
            resolve({
              success: false,
              error: `HTTP ${res.statusCode}: ${res.data}`,
              statusCode: res.statusCode
            });
          }
        },
        fail: (error) => {
          resolve({
            success: false,
            error: '网络请求失败: ' + error.errMsg
          });
        }
      });
    });
  }
  
  /**
   * 显示服务状态信息
   */
  static showServiceStatus(status) {
    let title = '';
    let content = '';
    
    if (status.success) {
      title = '服务状态正常';
      content = '✅ 阈值信息接口: 正常\n✅ 人脸识别接口: 正常\n\n所有服务运行正常，可以正常使用人脸识别功能。';
    } else {
      title = '服务状态异常';
      content = `❌ 服务检查失败\n\n错误信息: ${status.error || '未知错误'}\n\n请检查:\n1. 后端服务是否启动\n2. 网络连接是否正常\n3. 端口配置是否正确`;
    }
    
    wx.showModal({
      title: title,
      content: content,
      showCancel: false,
      confirmText: '知道了',
      confirmColor: status.success ? '#4CAF50' : '#FF5722'
    });
  }
}

module.exports = ServiceChecker;


